package org.example.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.time.Instant;
import java.util.Calendar;
import java.util.HashMap;
import java.util.TimeZone;


@Slf4j
@SpringBootTest
public class SpringBootTestDemo {

    //头部
    private HashMap<String,Object> header = new HashMap<>();
    //负载
    private HashMap<String,Object> payload = new HashMap<>();
    //秘钥
    private String secret = "!7yH9#lo";
    //过期时间(秒)
    private int expireTime = 180;
    @Test
    void createTest(){

        Calendar instance = Calendar.getInstance();
        instance.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        instance.add(Calendar.SECOND,expireTime);

        payload.put("id",10086);
        payload.put("name","mrchai");
        payload.put("age",38);

        String token = JWT.create()
//                .withHeader(header)
//                .withClaim("id","134012")
//                .withClaim("name","mrchai")
                .withPayload(payload)
                .withClaim("age",18)
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));

        log.debug("token:{}",token);
    }

    @Test
    void validateText(){
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoibXJjaGFpIiwiaWQiOjEwMDg2LCJleHAiOjE3MjMyNzkxOTksImFnZSI6MTh9.id87vVMMP3AvGVJn7s3gzyVGIB8VrhMd-SmjrMfAWdU";
//        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoic29mdGVlbSIsImlkIjoiMTAwMDEyIiwiZXhwIjoxNzIzMjc4ODU4NDY5LCJhZ2UiOjE4fQ.8uV8pYJHdv1qLd2oh5J_4rTyQBb_ubJp0m5ak5tT2y0";
        //构建验签对象
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
        DecodedJWT jwt = verifier.verify(token);
        log.debug("id:{}",jwt.getClaims());
    }
}
